#include "status.hpp"
#include "db_manager.hpp"
#include "../utils/ip_utils.hpp"
#include <sstream>
#include <ctime>
#include <iomanip>

std::vector<Status> Status::getAll() {
    std::vector<Status> statuses;
    auto* mysql = DBManager::getInstance().getConnection();
    
    if (!mysql) {
        throw std::runtime_error("无法获取数据库连接");
    }
    
    const char* query = "SELECT modid, cmdid, ip, port, caller, succ_cnt, err_cnt, ts, overload FROM ServerCallStatus";
    if (mysql_query(mysql, query)) {
        throw std::runtime_error(std::string("查询失败: ") + mysql_error(mysql));
    }
    
    MYSQL_RES* result = mysql_store_result(mysql);
    if (!result) {
        throw std::runtime_error(std::string("存储结果失败: ") + mysql_error(mysql));
    }
    
    MYSQL_ROW row;
    while ((row = mysql_fetch_row(result))) {
        Status status;
        status.modid = std::stoi(row[0]);
        status.cmdid = std::stoi(row[1]);
        status.ip = std::stoul(row[2]);
        status.port = std::stoi(row[3]);
        status.caller = std::stoul(row[4]);
        status.success_count = std::stoi(row[5]);
        status.error_count = std::stoi(row[6]);
        status.timestamp = std::stoll(row[7]);
        status.is_overload = (row[8][0] == '1');
        statuses.push_back(status);
    }
    
    mysql_free_result(result);
    return statuses;
}

bool Status::add(int modid, int cmdid, uint32_t caller, uint32_t ip, int port) {
    auto* mysql = DBManager::getInstance().getConnection();
    
    if (!mysql) {
        throw std::runtime_error("无法获取数据库连接");
    }
    
    char query[512];
    snprintf(query, sizeof(query),
             "INSERT INTO ServerCallStatus (modid, cmdid, caller, ip, port, succ_cnt, err_cnt, ts, overload) VALUES (%d, %d, %u, %u, %d, 0, 0, %lu, '0')",
             modid, cmdid, caller, ip, port, static_cast<unsigned long>(std::time(nullptr)));
    
    if (mysql_query(mysql, query) != 0) {
        throw std::runtime_error(std::string("插入失败: ") + mysql_error(mysql));
    }
    
    return true;
} 